<?php

require_once 'Base/TurnPostPeer.php';

/**
 * Generated Model class.
 */
class TurnPostPeer extends Base_TurnPostPeer
{
    /**
     * Ищем пустую позицию в очереди
     * 
     * @param string $date
     * @param turnTimeRow $times
     * @param turnPeer $turn
     * @return array
     */
    public function findEmptyPosition($date, $times, $turn)
    {
        $post_time = null;
        $currentDate = date('Y-m-d', time());
        $currentTime = date('H:i:s', time());
        foreach($times as $time){
            if ($currentDate == $date) {
                if (date('H:i:s', strtotime($time->time)) < $currentTime) {
                    continue;
                }
            }
            $select = $this->select();
            $select->where('turn_id = ?', $turn->getId())
                    ->where('post_date = ?', $date);
            $select->where('post_time = ?', $time->time);
            $row = $this->fetchRow($select);
            if ($row) {
                $post_time = null;
                continue;
            }
            $post_time = $time->time;
            break;
        }
        
        if ($post_time == null) {
            $result = $this->findEmptyPosition(date('Y-m-d', strtotime('+1 day', strtotime($date))), $times, $turn);
        } else {
            $result['post_date'] = $date;
            $result['post_time'] = $post_time;
        }
        return $result;
    }
}

